package com.harry.editsearchhistory.view;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.harry.editsearchhistory.R;
import com.harry.editsearchhistory.adapter.HistoryAdapter;
import com.harry.editsearchhistory.util.ActivityControler;
import com.harry.editsearchhistory.util.KeyboardUtils;
import com.harry.editsearchhistory.util.SearchHistoryUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author Martin-harry
 * @date 2022/3/2
 * @address
 * @Desc 主逻辑处理
 */
public class MainActivity extends AppCompatActivity {

    @BindView(R.id.activity_favo_add_et_search)
    EditText et_search;
    @BindView(R.id.activity_favo_add_tb_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.activity_favo_add_rv_list)
    RecyclerView rv_list;
    @BindView(R.id.activity_favo_add_tv_delAll)
    TextView tv_delAll;

    private SimpleDateFormat mFormat;
    private HistoryAdapter mAdapter;
    private List<String> list;
    private int HISTORY_MAX = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        ActivityControler.addActivity(this);
        initWidget();
        setAction();
    }

    /**
     * 初始化控件
     */
    private void initWidget() {
        //toolbar的控件
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false); // Toolbar掉标题栏
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        rv_list.setHasFixedSize(true);
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.setItemAnimator(new DefaultItemAnimator());// 设置item动画
        showSearchHistory();
    }

    /**
     * 从SP查询搜索历史，并按时间显示
     */
    private void showSearchHistory() {
        Map<String, String> hisAll = (Map<String, String>) SearchHistoryUtils.getAll(MainActivity.this);
        //将key排序升序
        Object[] keys = hisAll.keySet().toArray();
        Arrays.sort(keys);
        int keyLeng = keys.length;
        //这里计算 如果历史记录条数是大于 可以显示的最大条数，则用最大条数做循环条件，防止历史记录条数-最大条数为负值，数组越界
        int hisLeng = keyLeng > HISTORY_MAX ? HISTORY_MAX : keyLeng;
        list = new ArrayList<>();
        for (int i = 1; i <= hisLeng; i++) {
            list.add(hisAll.get(keys[keyLeng - i]));
        }

        mAdapter = new HistoryAdapter(MainActivity.this, list);
        rv_list.setAdapter(mAdapter);
    }

    /**
     * 搜索框监听
     */
    private void setAction() {
        // 搜索
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    KeyboardUtils.closeKeyboard(MainActivity.this, et_search); // 显示键盘
                    // TODO Connect Service TO Search

                    // 将搜索记录保存到SP中
                    saveSearchHistory(et_search.getText().toString().trim());
                    mAdapter.add(et_search.getText().toString(), 0);
                    return true;
                }
                return false;
            }
        });
        // 文字变动监听
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                //文字变动 ， 有未发出的搜索请求，应取消
//                if (mHandler.hasMessages(MSG_SEARCH)) {
//                    mHandler.removeMessages(MSG_SEARCH);
//                }
                //如果为空 直接显示搜索历史
//                if (TextUtils.isEmpty(s)) {
//                    showHistory();
//                } else {//否则延迟500ms开始搜索
//                    mHandler.sendEmptyMessageDelayed(MSG_SEARCH, 500); //自动搜索功能 删除
//                }
            }
        });
        // 适配器点击事件
        mAdapter.setOnItemClickListener(new HistoryAdapter.FavoAddClick() {
            @Override
            public void onItemClick(View view, int position) // 单击事件
            {
                et_search.setText(list.get(position).toString());
                et_search.requestFocus();
                KeyboardUtils.openKeyboard(MainActivity.this, et_search); // 显示键盘
                et_search.setSelection(list.get(position).toString().length()); // 将光标移动到最后

            }

            @Override
            public void onDelClick(View view, int position) // 删除
            {
                // 获取map中value对应的key，然后删除key对应的某条数据
                String key = SearchHistoryUtils.valueGetKey(SearchHistoryUtils.getAll(MainActivity.this), list.get(position).toString());
                SearchHistoryUtils.remove(MainActivity.this, key);
            }
        });
        // 清空
        tv_delAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearsearchHistory();
                mAdapter.remoceAll();
            }
        });
    }

    /**
     * 开启线程搜索
     */
    private Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg)
//        {
//            //搜索请求
//            showToast("搜索中。。。。");
//            //search(String.valueOf(mEditTextSearch.getText()));
//        }
    };


    /**
     * 将历史记录保存至sp中，key=当前时间(20160302133455，便于排序) ，value=关键字
     *
     * @param keyWords
     */
    private void saveSearchHistory(String keyWords) {
        //保存之前要先查询sp中是否有该value的记录，有则删除.这样保证搜索历史记录不会有重复条目
        Map<String, String> historys = (Map<String, String>) SearchHistoryUtils.getAll(MainActivity.this);
        for (Map.Entry<String, String> entry : historys.entrySet()) {
            if (keyWords.equals(entry.getValue())) {
                SearchHistoryUtils.remove(MainActivity.this, entry.getKey());
            }
        }
        mFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        // 以时间为key，保存搜索记录
        SearchHistoryUtils.put(MainActivity.this, "" + mFormat.format(new Date()), keyWords);
        // 刷新适配器

        mAdapter.notifyDataSetChanged();
    }


    /**
     * 清除历史记录
     */
    private void clearsearchHistory() {
        SearchHistoryUtils.clear(MainActivity.this);
        //同时刷新历史记录显示页面
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 删除多余的历史记录
     * 如果历史记录数量大于限定数量(10条)，则按key升序排序，删除前几条
     */
    private void delMoreSearchHistory() {

        Map<String, String> hisAll = (Map<String, String>) SearchHistoryUtils.getAll(MainActivity.this);
        if (hisAll.size() > HISTORY_MAX) {
            //将key排序升序
            Object[] keys = hisAll.keySet().toArray();
            Arrays.sort(keys);
            // LENGTH = 12 , MAX = 10 , I = 1,0,count =2;
            for (int i = keys.length - HISTORY_MAX - 1; i > -1; i--) {
                SearchHistoryUtils.remove(this, (String) keys[i]);
            }
        }

    }

    /**
     * 标题栏动作
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                ActivityControler.removeActivity(this);
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}

